import time
from datetime import datetime
from typing import Annotated
import uvicorn
from fastapi import FastAPI,  Query,HTTPException, Depends,BackgroundTasks
from fastapi.openapi.docs import get_swagger_ui_html, get_redoc_html

from sqlmodel import SQLModel, Field, create_engine, Session, select

from fastapi.staticfiles import StaticFiles





# 创建FastAPI实例，禁用掉FastAPI会自动生成Swagger UI和Redoc文档
app = FastAPI(docs_url=None, redoc_url=None)

# 静态文件挂载（路由与静态文件映射）
app.mount("/static", StaticFiles(directory="../statics"), name="static")


# 重新提供一个Swagger UI，相当于我们自己重写了这么一个路由
@app.get("/docs", include_in_schema=False)
def custom_swagger_ui():
    return get_swagger_ui_html(
        openapi_url = "/openapi.json",
        title = "Swagger UI for FastAPI",
        swagger_js_url="/static/swagger-ui-bundle.min.js",
        swagger_css_url="/static/swagger-ui.min.css"
    )

# 这里与Swagger UI一样，重新提供Redoc
@app.get("/redoc", include_in_schema=False)
def custom_redoc():
    return get_redoc_html(
        openapi_url = "/openapi.json",
        title = "Redoc for FastAPI",
        redoc_js_url="/static/redoc.standalone.js"
    )

def log_writer(message: str=""):
    with open("log.txt",mode="a+",encoding="utf-8") as log_file:
        # 模拟写入耗时
        time.sleep(3)
        # 获取前时间
        log_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        content = f"{log_time}: {message} \n"
        # 读log.txt的所有行到一个列表,只留最后1000行
        datas = log_file.readlines()[-999:]
        datas.append(content)
        log_file.writelines(datas)


@app.post("/send_log")
async def send_log(message: str, background_tasks: BackgroundTasks):
    background_tasks.add_task(log_writer,message)
    return {"message": "日志已写入"}





if __name__ == '__main__':
    app.debug = True
    uvicorn.run("main:app", host="127.0.0.1", port=8031, reload=True)

